# -*- coding: UTF-8 -*- 
import os,sys,urllib2,urllib,json,uuid
from urlparse import urlparse

def ReadFileAsContent(filename):
    #print filename  
    try:  
        with open(filename, 'rb') as f:  
            filecontent = f.read()  
    except Exception, e:  
        print 'The Error Message in ReadFileAsContent(): ' + e.message   
        return ''  
    return filecontent  

def get_content_type(filename):  
    import mimetypes  
    return mimetypes.guess_type(filename)[0] or 'application/octet-stream'  
  
def isfiledata(p_str):   
    import re  
      
    r_c = re.compile("^f'(.*)'$")  
    rert = r_c.search(str(p_str))  
    #rert = re.search("^f'(.*)'$", p_str)  
    if rert:  
        return rert.group(1)  
    else:  
        return None  
      
def encode_multipart_formdata(fields):  
    ''''' 
            该函数用于拼接multipart/form-data类型的http请求中body部分的内容 
            返回拼接好的body内容及Content-Type的头定义 
    '''  
    import random  
    import os  
    BOUNDARY = '----------%s' % ''.join(random.sample('0123456789abcdef', 15))  
    CRLF = '\r\n'  
    L = []  
    for (key, value) in fields:  
        filepath = isfiledata(value)  
        if filepath:  
            L.append('--' + BOUNDARY)  
            L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, os.path.basename(filepath)))  
            L.append('Content-Type: %s' % get_content_type(filepath))  
            L.append('')  
            L.append(ReadFileAsContent(filepath))   
        else:  
            L.append('--' + BOUNDARY)  
            L.append('Content-Disposition: form-data; name="%s"' % key)  
            L.append('')  
            L.append(value)    
    L.append('--' + BOUNDARY + '--')  
    L.append('')  
    body = CRLF.join(L)  
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY  
    return content_type, body

def redaTxt(fileName):
	if os.path.exists(fileName):
	    f = open(fileName, 'r')
	    return f.read()
	else:
	    f = open(fileName,'w')
	    return ""

def mkdir(path):
    path=path.strip()
    path=path.rstrip("\\")
    isExists=os.path.exists(path)
    if not isExists:
        os.makedirs(path)
        return True
    else:
        return False

#保存图片
def CheckImageAndPushImage(img):
    urlParseResult = urlparse(img)
    if urlParseResult.scheme != "https" and urlParseResult.scheme != "http":
        return img
    else:

        #下载图片
        path     = os.getcwdu() + "\\downloads\\"
        fileName = str(uuid.uuid1()) + ".jpg"
        filePath = path + fileName
        mkdir(path)
        req = urllib2.Request(img)
        try:
            conn = urllib2.urlopen(req)
            f = open(filePath,'wb')  
            f.write(conn.read())
            f.close()
        except Exception, e:
            print('Image Error')
            return False

        #上传图片    
    	f = ""
    	tb_token = redaTxt("cache_tb_token.txt")
    	cookies = redaTxt("cache_cookies.txt")
    	url = "https://stream.taobao.com/api/upload.api?appkey=tu&phone=false&folderId=0&_input_charset=utf-8&watermark=false"
    	form_data = [("name", fileName),("file", r"f'"+filePath+"'")]
    	content_type, boundary = encode_multipart_formdata(form_data)  

    	req = urllib2.Request(url,boundary)
    	req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36')
    	req.add_header('Referer', 'https://stream.taobao.com/plugin.htm?appkey=tu&single=true&tab=list&pageSize=14&maxNum=-1&ver=0.0.6')
    	req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % content_type)
    	req.add_header('Origin', 'https://stream.taobao.com')
    	req.add_header('X-Requested-With', 'XMLHttpRequest')
    	req.add_header('Accept-Encoding', 'gzip, deflate')
    	req.add_header('Cookie', cookies)
    	resp = urllib2.urlopen(req)
    	if resp.info().get('Content-Encoding') == 'gzip':
    		buf = StringIO( resp.read())
    		f = gzip.GzipFile(fileobj=buf)
    		data = f.read()
    	else:
    		data = resp.read()
    	try:
            res = json.loads(data)
            if res['success']:
                url =  str(res['object']['url'])
                return url.replace('https://img.alicdn.com/imgextra/','')
            else:
                return False
        except Exception, e:
            return False
	   #{"object":{"fileId":"183720236937541299","folderId":"0","url":"https://img.alicdn.com/imgextra/i4/376268372/TB25IPEqpXXXXchXpXXXXXXXXXX_!!376268372.jpg","fileName":"22.jpg","size":"160557","pix":"500x500"},"total":0,"success":true,"status":0,"message":""}


# if __name__== '__main__' :	
#     print CheckImageAndPushImage("https://gd4.alicdn.com/bao/uploaded/i4/TB1LQQWKXXXXXcTaXXXXXXXXXXX_!!1-item_pic.gif_500x500.jpg")